package info.hengha.book.action;

import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.google.gson.Gson;

import info.hengha.book.Author;
import info.hengha.book.Book;
import pw.yitree.work.mmsh.HibernateUtil;

/**
 * Servlet implementation class BookServlet
 */
@WebServlet("/books")
public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		Gson gson = new Gson();
		// response.setContentType("application/json; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		// request.setCharacterEncoding("utf-8");
		if (id != null && id.length() > 0) {
			Book book = null;
			try (Session session = HibernateUtil.getFactory().openSession()) {
				session.beginTransaction();
				book = session.get(Book.class, request.getParameter(":id"));
				session.getTransaction().commit();
				session.close();
			}
			if (book != null) {
				response.getWriter().append(gson.toJson(book));
			} else {
				response.setStatus(404); // 404 Not found
				response.getWriter().append(gson.toJson("not found"));
			}
		} else {
			List list = null;

			try (Session session = HibernateUtil.getFactory().openSession()) {
				session.getTransaction().begin();
				list = session.createQuery("from Book").list();
				session.getTransaction().commit();
			}
			response.getWriter().append(gson.toJson(list));
		}
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("utf-8");
		//arg1.setCharacterEncoding("utf-8");
		arg1.setContentType("application/json; charset=utf-8");
		super.service(arg0, arg1);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Gson gson = new Gson();
		String authorName = request.getParameter("author");
		String title = request.getParameter("title");
		Book book = new Book();
		book.setTitle(title);
		Author author = new Author();
		author.setName(authorName);
		book.setAuthor(author);

		try (Session session = HibernateUtil.getFactory().openSession()) {
			session.beginTransaction();
			session.save(author);
			session.save(book);
			session.getTransaction().commit();
			session.close();
		}
		response.setStatus(201); // 201 Created
		response.getWriter().append(gson.toJson(book));
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		Book book = null;
		Gson gson = new Gson();
		boolean isSuccess = false;
		String message = "";
		try (Session session = HibernateUtil.getFactory().openSession()) {
			session.getTransaction().begin();
			book = session.get(Book.class, id);
			session.delete(book);
			isSuccess = true;
			message = "ok";
			session.getTransaction().commit();
		}
		Hashtable t = new Hashtable();
		t.put("isSuccess", isSuccess);
		t.put("message", message);
		resp.getWriter().append(gson.toJson(t));
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		Gson gson = new Gson();
		Book book = null;
		boolean isSuccess = false;
		String message = "";
		try (Session session = HibernateUtil.getFactory().openSession()) {
			session.beginTransaction();
			book = session.get(Book.class, id);
			if (book != null) {
				String newAuthor = req.getParameter("author");
				String newTitle = req.getParameter("title");
				if (newAuthor != null) {
					book.getAuthor().setName(newAuthor);
				}
				if (newTitle != null) {
					book.setTitle(newTitle);
				}
				session.saveOrUpdate(book);
				isSuccess = true;
				message = "ok";
			} else {
				message = "not found";
				resp.setStatus(404); // 404 Not found
			}
			session.getTransaction().commit();
			session.close();
		}
		Hashtable t = new Hashtable();
		t.put("isSuccess", isSuccess);
		t.put("message", message);
		resp.getWriter().append(gson.toJson(t));
	}

}
